#!/bin/sh

GNB_DIR=$(dirname $0)

if [[ "$OSTYPE" == "linux-gnu" ]]; then
    GNB_BINARY=Linux_x86_64
elif [[ "$OSTYPE" == "darwin"* ]]; then
    GNB_BINARY=macOS
elif [[ "$OSTYPE" == "freebsd"* ]]; then
    GNB_BINARY=FreeBSD_amd64
elif uname | grep -Eqi "freebsd" ; then
    GNB_BINARY=FreeBSD_amd64
elif cat /etc/issue | grep -Eqi "Raspbian"; then
    GNB_BINARY=raspberrypi_ARMv7
else
    GNB_BINARY=Linux_x86_64
fi

#GNB_BINARY=FreeBSD_amd64
#GNB_BINARY=macOS
#GNB_BINARY=OpenBSD_amd64
#GNB_BINARY=raspberrypi_ARMv7
#GNB_BINARY=openwrt/ar71xx-generic
#GNB_BINARY=openwrt/ar71xx-mikrotik
#GNB_BINARY=openwrt/ar71xx-nand
#GNB_BINARY=openwrt/mvebu-cortexa9
#GNB_BINARY=openwrt/x86_64
#GNB_BINARY=openwrt/ramips-mt76x8

mkdir -p ${GNB_DIR}/output/
mkdir -p ${GNB_DIR}/output/tmp/ed25519

clear
echo
echo "Welcome to this GNB "road warrior" installer!"
echo

echo "How many nodes do you want to create?"
read -p "Num [3]: " num
until [[ -z "$num" || "$num" =~ ^[0-9]+$ && "$num" -le 200 ]]; do
    echo "$num: invalid input."
    read -p "Num [3]: " num
done
[[ -z "$num" ]] && num=3


lastnum=$(( $num + 1000 ))
for ((i=1; i<=$num; i ++))
do
    nodeid=$(( $i + 1000 ))
    portnum=$(( $i + 9000 ))
    #echo $i
    #echo $portnum
    mkdir -p ${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/security
    \cp -rf ${GNB_DIR}/conf_tpl/1001/script ${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/
    ${GNB_DIR}/bin/$GNB_BINARY/gnb_crypto -c -p ${nodeid}.private -k ${nodeid}.public
    \cp -rf ${nodeid}.public ${GNB_DIR}/output/tmp/ed25519
    mv ${nodeid}.public ${nodeid}.private ${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/security/
    >${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/route.conf

cat >${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/address.conf <<EOF
i|0|103.27.187.204|9001
i|0|39.108.10.191|9001
EOF

cat >${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/node.conf <<EOF
nodeid ${nodeid}
lisen  ${portnum}
EOF
for ((j=1; j<=$num; j ++))
do
echo "$(($j+1000))|10.1.0.${j}|255.255.255.0" >> ${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/route.conf
done

\cp -rf ${GNB_DIR}/{bin,sh,if_drv} ${GNB_DIR}/output/gnb_${nodeid}/

done
for ((i=1; i<=$num; i ++))
do
    nodeid=$(( $i + 1000 ))
    \cp -rf ${GNB_DIR}/output/tmp/ed25519 ${GNB_DIR}/output/gnb_${nodeid}/conf/${nodeid}/
done

cd ${GNB_DIR}/output/ && rm -rf tmp && cd ..
echo 
echo "The configuration file of 1001-${lastnum} node has been output to DIR: ${GNB_DIR}/output/ "
echo 
ls ${GNB_DIR}/output
echo
exit
